from rest_framework import exceptions
from rest_framework.decorators import api_view, authentication_classes, permission_classes

from datacenter.models import Entity
from datacenter.services import data_service

from libs.utils import parse_page_params
from libs.auth.openapi import openapi_auth
from libs.decorators import required_query_parameters
from libs.simple_responses import api_success


@api_view(['GET'])
@authentication_classes([])
@permission_classes([])
@openapi_auth()
@required_query_parameters(['entity_key'])
def data(request):
    entity_key = request.query_params.get('entity_key')
    last_updated_at = request.query_params.get('last_updated_at')
    entity_instance = Entity.objects.filter(key=entity_key).first()
    if not entity_instance:
        raise exceptions.ParseError('not found')

    certificate_data = request.certificate_data
    entities = certificate_data.get('entities', [])

    entity = None
    for e in entities:
        if e.get('key') == entity_key:
            entity = e
            break
    if not entity:
        raise exceptions.ParseError('access denied')

    fields = entity.get('fields')
    ext_filter = entity.get('ext_filter')
    page, page_size = parse_page_params(request)
    total, items = data_service.get_handler(entity_instance)(
        entity_instance,
        ext_filter=ext_filter,
        last_updated_at=last_updated_at,
        page=page,
        page_size=page_size
    )

    new_items = []
    for item in items:
        new_items.append({field['field']: item.get(field['field']) for field in fields})

    data = {
        'total': total,
        'items': new_items
    }
    return api_success(data=data)
